//
//  MTOpenRedpackViewController.swift
//  MT
//
//  Created by ooops on 2019/12/23.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa

class MTOpenRedpackViewController: BaseViewController {
    
    private var openRedpackModel: MTOpenRedpackModel?
    
    private var msgId: String = ""
    
    private var type: MTRedpacketType = .default
    
    private var callback: (() -> Void)?
    
    override init() {
        super.init()
    }
    
    convenience init(_ openRedpackModel: MTOpenRedpackModel, msgId: String, type: MTRedpacketType, callback: (() -> Void)?) {
        self.init()
        self.openRedpackModel = openRedpackModel
        self.msgId = msgId
        self.type = type
        self.callback = callback
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0x000000, alpha: 0.5)
        view.addSubview(openRedpack)
        view.addSubview(closeBtn)
        
        openRedpack.frame = CGRect(x: 0, y: 0, width: 269.auto(), height: 389.auto())
        openRedpack.center = view.center
        
        closeBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(openRedpack.snp.bottom).offset(17.auto())
            make.width.height.equalTo(80)
        }
    }
    
    
    lazy var openRedpack: MTOpenRedpackInputView = {
        let v = MTOpenRedpackInputView()
        v.openRedpackModel  = self.openRedpackModel
        v.delegate = self
        v.msgId = self.msgId
        v.type = self.type
        v.callback = callback
        return v
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        //btn.setTitle("关闭", for: .normal)
        btn.setImage(UIImage(named: "icon_close"), for: .normal)
        btn.addTarget(self, action: #selector(MTOpenRedpackViewController.close), for: .touchUpInside)
        return btn
    }()
    
    @objc private func close() {
        self.dismiss(animated: true, completion: nil)
    }

}

extension MTOpenRedpackViewController: MTOpenRedpackInputViewDelegate {
    /// 点击打开红包按钮
    func openRedpack(_ view: MTOpenRedpackInputView, model: MTOpenRedpackModel?, msgId: String, type: MTRedpacketType, callback: (() -> Void)?) {
        if let repackId = self.openRedpackModel?.result?.sendId {
            MTRedpackTool.default.openRedpack(redpacketId: repackId) { [weak self] (redpackModel, isSuccess) in
                guard let weakSelf = self else { return }
                /// 红包领取
                redpackModel?.sendType = model?.sendType ?? -1
                //redpackModel?.result?.status = .clearance
                if isSuccess, let status = redpackModel?.result?.status {
                    /// 如果是已经打开过的红包 / 已经领取完毕
                    var s: MTOpenRedpackStatus = .unkonw
                    switch status {
                    case .owner:
                        weakSelf.redpackDetail(redpackModel: redpackModel!)
                    case .opened:
                        weakSelf.redpackDetail(redpackModel: redpackModel!)
                        s = .opened
                        if let m = redpackModel?.result, m.outNum == m.num {
                            s = .clearance
                        }
                    case .clearance:
                        weakSelf.redpackDetail(redpackModel: redpackModel!)
                        s = .clearance
                    case .invalid:
                        view.openRedpackModel = redpackModel
                        s = .invalid
                    case .failed:
                        break
                    default:
                        weakSelf.openRedpack(redpackModel: redpackModel!, msgId: msgId, type: type, callback: callback)
                    }
                    
                    if let info = MTRedpacketInfoDB.shareInstance.quaryData(msgId: msgId).first, (s == .opened || s == .clearance || s == .invalid) {
                        info.status = s
                        MTRedpacketInfoDB.shareInstance.updateRedpacketMessage(info)
                        weakSelf.callback?()
                    }
                }
            }
        }
    }
    
    /// 红包领取详情
    /// - Parameters:
    ///   - presentViewController: presentViewController description
    ///   - redpackModel: redpackModel description
    private func redpackDetail(redpackModel: MTOpenRedpackModel) {
        self.close()
        DispatchQueue.main.async {
            self.navigationVC?.pushViewController(MTOpenRedpackDetailViewController(redpackModel), animated: true)
        }
    }
    
    
    /// 弹出领红包界面
    /// - Parameters:
    ///   - presentViewController: presentViewController description
    ///   - redpackModel: redpackModel description
    private func openRedpack(redpackModel: MTOpenRedpackModel, msgId: String, type: MTRedpacketType, callback: (() -> Void)?) {
        let nav = BaseNavController(rootViewController: MTOpenRedpackViewController(redpackModel, msgId: msgId, type: type, callback: callback))
        let presentTransition: MTModalTransition = MTModalTransition()
        nav.transitioningDelegate = presentTransition
        nav.modalPresentationStyle = .custom
        nav.modalTransitionStyle = .crossDissolve
        DispatchQueue.main.async {
            self.navigationVC?.present(nav, animated: true, completion: nil)
        }
    }
    
    func openRedpackDetail(_ view: MTOpenRedpackInputView, model: MTOpenRedpackModel?) {
        self.close()
        navigationVC?.pushViewController(MTOpenRedpackDetailViewController(self.openRedpackModel!), animated: true)
    }
}

extension MTOpenRedpackViewController {
    
    override func yp_navigationBarTintColor() -> UIColor! {
        return .clear
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [YPNavigationBarConfigurations.backgroundStyleColor]
    }
    
    override func yp_navigationBackgroundColor() -> UIColor! {
        return .clear
    }
    
}
